<?php
/**
 +------------------------------------------------------------------------------
 * Agent分销商用户信息操作
 +------------------------------------------------------------------------------
 * @package  app
 * @author   alpha <QQ:411083658>
 * @date 2013-9-12
 * @time  下午13:38:07
 +------------------------------------------------------------------------------
 */
class Agent {
	protected $dao,$daolog,$post,$platform='SMW01';
	protected $userid=0;
	protected $debug=array();
	protected $isdebug = 0,$isecho = 0;
	protected $err_code = '';
	/**
	 * 实例化分销商用户信息类函数
	 * */
	function __construct(){
		$this->dao = M('UserAgent');
		$this->daolog = M('UserAgentLog');
	}
	/**
	 * 分销商用户列表
	 * @param array     $_arr=array(
	 * 					'user_id'=>用户ID,
	 * 					'contract_sn'=>合同编号,
	 * 					'stype'=>分销角色类型,
	 * 					'pay_status'=>付款状态,
	 * 					'status'=>申核状态,
	 * 					'isclose'=>开通状态
	 * 					)
	 * @param array 	$arr_area=array(
	 * 					'province' => 省份ID，
	 * 					'city' => 城市ID，
	 * 					'area' => 区域ID
	 * 					)
	 * @return array
	 * */
	 function agent_list($_arr=array(),$arr_area=array(),$limit = '0,20',$order = 'id DESC'){
	 	$this->dao = M('UserAgent');
	 	// 分销商用户列表相关查询
	 	$model = $this->dao;
		/*$where = array();
		if($_arr != 'all'){
			foreach ($_arr as $key => $value) {
				$where[$key] = $value;
			}
		}*/
		$where = '';
		if($_arr != 'all'){
			foreach ($_arr as $key => $value) {
				if(empty($where)){
					$where = $key."='".$value."'";
				}else{
					$where .= " AND ".$key."='".$value."'";
				}
			}
		}
		
		foreach ($arr_area as $key => $value) {
			if(empty($where)){
				if(!empty($value)&&$value!=0){
					$where = $key."='".$value."'";
				}
			}else{
				if(!empty($value)&&$value!=0){
					$where .= " AND ".$key."='".$value."'";
				}
			}
		}
		if($_arr != 'all'){
			if (strtolower ( $limit ) == 'all') {
				return $model->where($where)->count ();
			}
			$res = $model->where($where)->order ( $order )->limit ( $limit )->select();
		}else{
			$res = $model->where($where)->order ( $order )->select();
			//dump($model->getLastSql());
		}
		return $res;
	 }
	 /**
	 * 下级分销商用户列表
	 * @param array     $_arr=array(
	 * 					'user_id'=>用户ID,
	 * 					'contract_sn'=>合同编号,
	 * 					'stype'=>分销角色类型,
	 * 					'pay_status'=>付款状态,
	 * 					'status'=>申核状态,
	 * 					'isclose'=>开通状态,
	 * 					'province' => 省份ID，
	 * 					'city' => 城市ID，
	 * 					'area' => 区域ID
	 * 					)
	 * @return array
	 * */
	 function agent_Lower_list($_arr=array(),$limit = '0,20',$order = 'id DESC'){
	 	$this->dao = M('UserAgent');
		$user = M('user');
	 	// 分销商用户列表相关查询
	 	$model = $this->dao;
		$where = array();
		if($_arr != 'all'){
			/*foreach ($_arr as $key => $value) {
				$where[$key] = $value;
			}*/
			$where = $_arr;
		}
		if (strtolower ( $limit ) == 'all') {
			$ret = $model->where($where)->count ();
			
			return $ret;
		}
		$res = $model->where($where)->order ( $order )->limit ( $limit )->select();
		$data = $user->field('id,username')->select();
		
		foreach($data as $value){
			$list[$value['username']] = $value['id'];
		}
		foreach($res as $key => $value){
			$res[$key]['username'] = array_search($value['user_id'], $list);
		}
		return $res;
	 }
	 /**
	 * 获取专营商订单结算比较列表
	 * @param array     $_arr=array(
	 * 					'agent_id'=>专营商ID
	 * 					)
	 * @return array
	 * */
	 function agent_profit_list($_arr=array(),$limit = '0,5',$order = 'id DESC'){
	 	$this->dao = M('UserAgentProfit');
	 	$model = $this->dao;
		$where = array();
		if($_arr != 'all'){
			$where = $_arr;
		}
		if (strtolower ( $limit ) == 'all') {
			$ret = $model->where($where)->count();
			return $ret;
		}
		$list = $model->where($where)->order($order)->limit($limit)->select();
		return $list;
	 }
	 /**
	  * 添加用户
	  * @param array    $info			要添加的数据
	  * @return array 	成功返回 {"status":"1","msg":"信息","data":data,"id":序列号} 失败返回 {"status":"0","msg":"信息","data":data}
	  * */
	function agent_profit_add($info=array()){
		$this->dao = M('UserAgentProfit');
		unset($this->post);
		$this->post = $info;
		$resid = $this->insert();
		if(false !== $resid){
			$res=array('id'=>$resid);
			return $this->_suc($res,'添加成功');
		}else{
			return $this->_err("添加失败请重试");
		}
	}
	function agent_profit_del($id){
		$this->dao = M('UserAgentProfit');
		$ret = self::delete_ext($id);
		if(false !== $ret){
			$res=array('id'=>$ret);
			return self::_suc($res,'删除成功');
		}else{
			return self::_err("删除失败请重试");
		}
	}
	/**
	 * 获取专营商附属管理区域列表
	 * @param array     $_arr=array(
	 * 					'agent_id'=>专营商ID
	 * 					)
	 * @return array
	 * */
	 function agent_attached_list($_arr=array(),$limit = '0,5',$order = 'id DESC'){
	 	$this->dao = M('UserAgentAttached');
	 	$model = $this->dao;
		$where = array();
		if($_arr != 'all'){
			$where = $_arr;
		}
		if (strtolower ( $limit ) == 'all') {
			$ret = $model->where($where)->count();
			return $ret;
		}
		$list = $model->where($where)->order($order)->limit($limit)->select();
		return $list;
	 }
	 /**
	  * 添加附属管理区域
	  * @param array    $info			要添加的数据
	  * @return array 	成功返回 {"status":"1","msg":"信息","data":data,"id":序列号} 失败返回 {"status":"0","msg":"信息","data":data}
	  * */
	function agent_attached_add($info=array()){
		$this->dao = M('UserAgentAttached');
		unset($this->post);
		$this->post = $info;
		$resid = $this->insert();
		if(false !== $resid){
			$res=array('id'=>$resid);
			return $this->_suc($res,'添加成功');
		}else{
			return $this->_err("添加失败请重试");
		}
	}
	function agent_attached_del($id){
		$this->dao = M('UserAgentAttached');
		$ret = self::delete_ext($id);
		if(false !== $ret){
			$res=array('id'=>$ret);
			return self::_suc($res,'删除成功');
		}else{
			return self::_err("删除失败请重试");
		}
	}
	 /**
	 * 会员资产列表
	 * @param array     $_arr=array(
	 * 					'user_id'=>用户ID,
	 * 					'agent_id'=>专营商ID,
	 * 					'id'=>专营商关联会员表 ID
	 * 					)
	 * @return array
	 * */
	 function agent_member_list($_arr=array(),$limit = '0,20',$order = 'u.createtime DESC'){
	 	$this->dao = M();
	 	$model = $this->dao;
		$where = array();
		if($_arr != 'all'){
			$where = $_arr;
		}
		if (strtolower ( $limit ) == 'all') {
			$ret = $model->table('user_type ut')->join('user_b2b ub ON ub.user_id = ut.user_id')->join('user u ON u.id = ut.user_id')->where($where)->count();
			return $ret;
		}
		$list = $model->table('user_type ut')->join('user_b2b ub ON ub.user_id = ut.user_id')->join('user u ON u.id = ut.user_id')->where($where)->field('ut.id,ut.agent_id,ut.user_id,ub.realname,ub.company,ub.tel,ub.mobile,ub.province,ub.city,ub.area,ub.address,ub.status,u.username,u.email,u.createtime')->order($order)->limit($limit)->select();
		//echo $model->getLastSql();
		$temp_userid = '';
		foreach ($list as $key => $value) {
			if(empty($temp_userid)){
				$temp_userid = $value['user_id'];
			}else{
				$temp_userid .=','.$value['user_id'];
			}
		}
		$user_money = M('UserMoney');
		$where = array();
		$where['platform'] = 'SMW01';
		$where['userid'] = array('IN',$temp_userid);
		$user_money_list = $user_money->where($where)->select();
		$temp_list = array();
		foreach ($list as $l_key => $l_value) {
			$temp_list[$l_key] = $l_value;
			foreach ($user_money_list as $value) {
				if($l_value['user_id'] == $value['userid']){
					$temp_list[$l_key][$value['subject']] = $value['value'];
				}
			}
		}
		return $temp_list;
	 }
	 
	/**
	 * 获取分销平台信息
	 * @param int     $id 分销平台信息用户ID
	 * @param int     $userid 用户ID
	 * @return array
	 * */
	 function get_agent_detail($id,$userid=0){
		$this->dao = M('UserAgent');
		if($userid != 0){
			return $this->select_ext('',array('user_id'=>$userid),'*',false);
		}
		return $this->select($id);
	 }
	 /**
	 * 分销商家平台信息操作日志列表
	 * @param array     $_arr=array(
	 * 					'userid'=>用户ID
	 * 					)
	 * @return array
	 * */
	 function agent_log_list($_arr=array(),$limit = '0,20',$order = 'id DESC',$isall = true){
		$model = M('UserAgentLog');
		$where = array();
		if($_arr != 'all'){
			foreach ($_arr as $key => $value) {
				$where[$key] = $value;
			}
		}
		if($isall !== false){
			if (strtolower ( $limit ) == 'all') {
				return $model->where($where)->count ();
			}
			$rel = $model->where($where)->order ( $order )->limit ( $limit )->select();
			return $rel;
		}else{
			$rel = $model->where($where)->order ( $order )->select();
			return $rel;
		}
	 }
	 /**
	  * 查询用户权限
	  * @param int	 	$userid	用户ID
	  * @return array
	  * */
	 function get_role($userid){
	 	return $this->select_ext(M('RoleUser'),array('user_id' => $userid),"role_id");
	 }
	 /**
	  * 添加用户
	  * @param array    $info			要添加的数据
	  * @param array 	$field_exist	设置不可重复的字段
	  * @param array 	$field_null		设置不可为空的字段
	  * @param int	 	$userid			帐户ID
	  * @param int	 	$action_userid	操作人编号
	  * @param varchar 	$remark			操作特殊备注
	  * @return array 	成功返回 {"status":"1","msg":"信息","data":data,"id":序列号} 失败返回 {"status":"0","msg":"信息","data":data}
	  * */
	function agent_add($info=array(),$field_exist=array(),$field_null=array(),$userid=0,$action_userid=0,$remark=null){
		$this->dao = M('UserAgent');
		unset($this->post);
		foreach ($field_null as $key => $value) {
			if(empty($info[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $info[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post = $info;
		$resid = $this->insert();
		if(false !== $resid){
			$log['userid'] = $userid;
			$log['type'] = 1;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('id'=>$resid);
			return $this->_suc($res,'注册成功');
		}else{
			return $this->_err("添加失败请重试");
		}
	}
	/**
	 * 修改用户
	 * @param array    	$info			要更新的数据
	 * @param array 	$field_exist	设置不可重复的字段
	 * @param array 	$field_null		设置不可为空的字段
	 * @param int	 	$userid			帐户ID
	 * @param int	 	$action_userid	操作人编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function agent_edit($info=array(),$field_exist=array(),$field_null=array(),$userid=0,$action_userid=0,$remark=null){
		$this->dao = M('UserAgent');
		unset($this->post);
		$this->userid = $info['id'];
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
		foreach ($field_null as $key => $value) {
			if(empty($info[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $info[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post['id'] = $this->userid;
		$this->post = $info;
		$ret = $this->update();
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 5;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 付款状态
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function agent_pay_status($id,$userid=0,$action_userid=0,$status=0,$remark=null){
		$this->dao = M('UserAgent');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['pay_status'] = $status;
		$ret = $this->update();
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 2;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'设置支付状态成功');
		}else{
			return $this->_err("设置支付状态失败请重试");
		}
	}
	/**
	 * 审核用户
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function agent_status($id,$userid=0,$action_userid=0,$status=0,$remark=null){
		$this->dao = M('UserAgent');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['status'] = $status;
		$ret = $this->update();
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 3;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'设置审核状态成功');
		}else{
			return $this->_err("设置审核状态失败请重试");
		}
	}
	/**
	 * 开通状态
	 * @param int    	$id				要更新的数据编号
	 * @param int	 	$userid			帐户ID 
	 * @param int 		$action_userid	操作人编号
	 * @param int 		$status			状态编号
	 * @param int		$roleid			权限编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param array 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function agent_isclose($id,$userid=0,$action_userid=0,$status=0,$roleid=0,$remark=null){
		$this->dao = M('UserAgent');
		unset($this->post);
		$this->userid = intval($id);
		if(empty($this->userid)||intval($status) <=0){
			return $this->_err("ID或其它参数有误!");
		}
		$this->post['id'] = $this->userid;
		$this->post['isclose'] = $status;
		$ret = $this->update();
		
		if(false !== $ret){
			$log['userid'] = $userid;
			$log['type'] = 4;
			$log['action_userid'] = $action_userid;
			$log['ctime'] = time();
			if($remark != null){
				$log['remark'] = $remark;
			}
			$this->insert_ext($this->daolog,$log);
			if($status==2){
				$this->set_role_status($roleid,1,$userid);
			}else{
				$this->set_role_status($roleid,0,$userid);
			}
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'设置开通状态成功');
		}else{
			return $this->_err("设置开通状态失败请重试");
		}
	}
	public function set_role_status($roleid,$status,$userid){
		if(!empty($this->platform)){
			if(!empty($roleid)){
				$ret = $this->select_ext(M('RoleUser'),array('role_id'=>$roleid,'user_id'=>$userid),'id',false);
				//dump($ret);
				if(empty($ret)){
					$role['role_id'] = $roleid;
					$role['user_id'] = $userid;
					$role['ctime'] = time();
					$this->insert_ext(M('RoleUser'),$role);
				}
			}
			$ret = $this->select_ext(M('UserExt'),array('userid'=>$userid,'element'=>'status','platform'=>$this->platform),'id,value',false);
			if(empty($ret)){
				$ext['value'] = $status;
				$ext['userid'] = $userid;
				$ext['element'] = "status";
				$ext['title'] = "状态";
				$ext['platform'] = $this->platform;
				$this->insert_ext(M('UserExt'),$ext);
			}else{
				if($ret['value']!=$status){
					$this->update_ext(M('UserExt'),array('value'=>$status),$ret['id']);
				}
			}
		}
	}
	/**
	 * 一键更新所有专营商关联会员
	 * @param int 		$action_userid	操作人编号
	 * @param varchar 	$remark			操作特殊备注
	 * @param json 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	public function relation_all($action_userid=0,$remark=null){
		$ua = M('UserAgent');
		$agent_list = $ua->where(array('isclose'=>2))->select();
		$num_agent_list = count($agent_list);
		$num_relation = 0;
		foreach ($agent_list as $key => $value) {
			$arr_area = array();
			$arr_area['province'] = $value['vesting_province'];
			$arr_area['city'] = $value['vesting_city'];
			$arr_area['area'] = $value['vesting_area'];
			$res = self::relation($value['user_id'],$action_userid,$value['stype'],$arr_area,true,$remark);
			$arr=object_array(json_decode($res));
			if($arr['status']==1){
				++$num_relation;
			}
		}
		if($num_agent_list == $num_relation){
			return self::_suc(array('id'=>0),'全部成功关联!专营商共'.$num_agent_list.'个,关联'.$num_relation.'条');
		}else{
			return self::_err('关联失败，请重试!专营商共'.$num_agent_list.'个,关联'.$num_relation.'条,异常ID'.$this->err_code);
		}
	}
	/**
	 * 更新专营商关联云采购会员
	 * @param int	 	$userid			专营商ID 
	 * @param int 		$action_userid	操作人编号
	 * @param int		$stype			专营商类型
	 * @param array 	$area			专营区域
	 * @param bool	 	$isall			是否全部专营商关联会员
	 * @param varchar 	$remark			操作特殊备注
	 * @param json 	成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	public function relation($userid=0,$action_userid=0,$stype=0,$area=array(),$isall=false,$remark=null){
		if($isall == false){
			$agent_detail = self::get_agent_detail(0,$userid);
			if(!empty($agent_detail) && $stype == $agent_detail['stype']){
				foreach ($area as $key => $value) {
					if($agent_detail['vesting_'.$key] != $value){
						return self::_err("操作或数据不合法!");
					}
				}
			}else{
				return self::_err("操作或数据不合法!");
			}
		}
		
		$where = array();
		switch ($stype) {
			case 1:
				$where['province'] = $area['province'];
				break;
			case 2:
				$where['province'] = $area['province'];
				$where['city'] = $area['city'];
				break;
			case 3:
				$where['province'] = $area['province'];
				$where['city'] = $area['city'];
				$where['area'] = $area['area'];
				break;
			default:
				return self::_err("该帐户不在此操作权限内!");
				break;
		}
		$user_b2b = self::select_ext(M('UserB2b'),$where,'user_id',true);
		$user_type = self::select_ext(M('UserType'),array('agent_id'=>$userid),'id,agent_id,user_id',true);
		//$data = array();
		$ut = array();
		$ub = array();
		if(!empty($user_type)){
			foreach ($user_type as $key => $value) {
				$ut[$value['id']] = $value['user_id'];
			}
		}
		if(empty($user_b2b)){
			$this->err_code = $this->err_code.'|'.$userid;
			return self::_err("没有可关联的用户!");
		}
		foreach ($user_b2b as $key => $value) {
			$ub[] = $value['user_id'];
		}
		unset($user_type);
		unset($user_b2b);
		$ret = 0;
		foreach ($ub as $key => $value) {
			if(!in_array($value, $ut)){
				$ext['agent_id'] = $userid;
				$ext['user_id'] = $value;
				$ret = self::insert_ext(M('UserType'),$ext);
			}else{
				/*$ut_model = M('UserType');
				$data['id']=array_search($value['user_id'],$ut);
				$data['agent_id']=$userid;
				$data['user_id']=$value['user_id'];
				$ret = $ut_model->add($data,array(),true);
				$this->debug = $ut_model->getLastSql();*/
				$ext['agent_id'] = $userid;
				$ext['user_id'] = $value;
				$ret = self::update_ext(M('UserType'),$ext,array_search($value,$ut));
			}
		}
		if(!empty($ut)){
			foreach ($ut as $key => $value) {
				if(!in_array($value, $ub)){
					$this->dao = M('UserType');
					$ret = self::delete_ext(array_search($value,$ut));
				}
			}
		}
		
		unset($ut);
		unset($ub);
		$res=array('id'=>$ret);
		return self::_suc($res,'区域专营关联会员成功更新!');
	}
	/**
	 * 校验用户名是否合法
	 * */
	private function _check($fn,$val){
		$model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
	}
	/**
     * 查询某个字段是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回false，不存在返回true
     */
    private function field_exist($fn,$val){
        $model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
		//$this->debug = $model->getlastsql();
        if($rel === false || empty($rel) || $rel['id'] == $this->userid){
            return true;
        }else{
            return false;
        }
    }
    /**
	 *请求接口类型异常
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _err($str="暂无相关信息") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			return $this->myjson($res);
		}
		
	}//end _err
	
	/**
	 *请求成功返回
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _suc($arr=array(),$str="操作成功") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			return $this->myjson($res);
		}
		
	}//end _suc
	/**
	 * 对url或其它字符转义
	 * */
	private function myjson($code) {
		$code = json_encode ( $this->urlencodeAry ( $code ) );
		return urldecode ( $code );
		//return $code;
	}
	private function urlencodeAry($data) {
		if (is_array ( $data )) {
			foreach ( $data as $key => $val ) {
				$data [$key] = $this->urlencodeAry ( $val );
			}
			return $data;
		} else {
			return urlencode ( $data );
		}
	}
	
	/**
	 * 操作插入数据表
	 * */
	private function insert(){
		$model = $this->dao;
		$_POST = $this->post;
		if (false === $model->create ()) {
			return false;
		}
		$result = $model->add ();
		//F('insert_sql'.time(),$model->getLastSql());
		if ($result !== false) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作更新数据表
	 * */
	private function update(){
		$model = $this->dao;
		if (false === $model->create ($this->post)) {
			return false;
		}
		$result = $model->save ();
		$this->debug = $model->getlastsql();
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作删除数据表
	 * */
	private function delete(){
		$model = $this->dao;
		$result = $model->delete ($this->userid);
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作查询数据表
	 * @param $id 查询用户ID
	 * @return 如果存在返回用户信息，不存在返回false，参数$id空返回所有用户信息
	 * */
	private function select($id){
		$model = $this->dao;
		if(!empty($id)){
			$result = $model->find ($id);
			return $result;
		}else{
			$result = $model->select ();
			return $result;
		}
	}
	/**
	 * 操作添加用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function insert_ext($table_ext,$field_value = array()){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		$this->post = $field_value;
		$rel = $this->insert();
		return $rel;
	}
	/**
	 * 操作更新用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function update_ext($table_ext,$field_value = array(),$id){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		if(!empty($id)){
			$field_value['id'] = $id;
			$this->post = $field_value;
		}
		$rel = $this->update();
		return $rel;
	}
	/**
	 * 操作删除用户关联扩展或附属数据表
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function delete_ext($id){
		if(!empty($id)){
			$this->userid = $id;
		}
		$rel = $this->delete();
	}
	/**
	 * 操作查询用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回查询信息，不存在返回false
	 * */
	private function select_ext($table_ext,$field_value = array(),$field = "*",$isall = true){
		if(!empty($table_ext)){
			$this->dao = $table_ext;
		}
		$rel = $this->select_all($field_value,$field,$isall);
		return $rel;
	}
	/**
     * 自定义查询条件查询数据
	 * @param array $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回所有信息，不存在返回false
     */   
    private function select_all($field_value = array(),$field = "*",$isall = true){
        $model = $this->dao;
		$where = "";
		foreach ($field_value as $key => $value) {
			if(empty($where)){
				$where = $key."='".$value."'";
			}else{
				$where .= " AND ".$key."='".$value."'";
			}
		}
		$rel = array();
		if($isall == true){
			$rel = $model->field($field)->where($where)->select();
			$this->debug = $model->getlastsql();
		}else{
			$rel = $model->field($field)->where($where)->find();
			$this->debug = $model->getlastsql();
		}
        if(!empty($rel)){//$rel !== false ||
            return $rel;
        }else{
            return false;
        }
    }
	/**
     * 查询用户是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回一条用户信息，不存在返回false
     */
    private function select_field($fn,$val){
        $model = $this->dao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
    }
}